﻿using System;
using System.Web;
using System.Web.Security;
using Business;
using Common.Constants;

namespace ServicesDirectory
{
    public partial class LogOn : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["UserInfo"] != null)
            {
                if (!String.IsNullOrEmpty(Request.QueryString["fn"]))
                {
                    Session.Remove("UserInfo");
                    var cookie = new HttpCookie("usercookie") {Expires = DateTime.Now.AddDays(-1d)};
                    Response.Cookies.Add(cookie);
                    Response.Redirect("LogOn.aspx");
                }
                Response.Redirect("Default.aspx");
            }

        }

        protected void BtnLoginClick(object sender, EventArgs e)
        {
            var account = TxtUserName.Text;
            var password = TxtPassWord.Text;
            var userBusiness = new UserBusiness();
            var result = userBusiness.ValidateUser(account, password);
            if (result)
            {
                var user = userBusiness.GetUser(account, password);
                var role = Enum.GetName(typeof(Role), Role.Normal);
                if (user.Role == (int)Role.Normal)
                {
                    if (FormsAuthentication.Authenticate(role, role))
                    {
                        Session["UserInfo"] = user;
                        if(cbRemember.Checked)
                        {
                            var cookie = new HttpCookie("usercookie")
                                             {Value = user.Account, Expires = DateTime.Now.AddDays(15)};
                            Response.Cookies.Add(cookie);
                        }
                        FormsAuthentication.RedirectFromLoginPage(role, false);
                    }
                }
            }
            else
            {
                //Response.Write(@"<script language='text/javascript'>alert('Username or Password wrong!');</script>");
                lblStatus.Text = "Username or Password wrong!";
            }
        }
    }
}
